﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace MEF_Import_And_Export
{
    public class CompositionStarter<TParams>
    {
        private CompositionContainer _container;

        public CompositionStarter(params ComposablePartCatalog[] catalogs)
        {
            var aggregate = new AggregateCatalog(catalogs);
            _container = new CompositionContainer(aggregate);
        }

        public CompositionStarter(CompositionContainer container)
        {
            if (container == null)
                throw new ArgumentNullException("container");

            _container = container;
        }

        public CompositionStarter()
        {
            _container = new CompositionContainer(new AssemblyCatalog(Assembly.GetCallingAssembly()));
        }

        public void Start(TParams parameters)
        {
            var startables = _container.GetExportedValues<IStartable<TParams>>();
            foreach (var startable in startables)
            {
                startable.Start(parameters);
            }
        }

        public void Start()
        {
            Start(default(TParams));
        }

        public void Stop()
        {
            if (_container == null)
                throw new InvalidOperationException("stop can only be called once");
          
            _container.Dispose();
            _container = null;
        }

    }

    [InheritedExport]
    public interface IStartable<TParams>
    {
        void Start(TParams parameters);
    }

    public class WpfStartable:IStartable<object>
    {
        [Import]
        public Window Window { get; set; }

        public void Start(object parameters)
        {
            Application.Current.MainWindow = Window;
            Window.Show();
        }
    }
}
